﻿using System;
using System.Web;
using System.Globalization;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Threading;
using System.Configuration;
using System.Web.Util;
using System.Security.Permissions;
using System.Web.Hosting;
using System.Security.Principal;
using System.Security;
using System.Diagnostics;
using System.Web.Configuration;
using MySql.Data.MySqlClient;

namespace Reviewer.Security
{
    internal sealed class MySqlConnectionHolder
    {
        internal MySqlConnection connectionInstance;
        private bool hasBeenOpened;

        internal MySqlConnectionHolder(MySqlConnection connection)
        {
            this.connectionInstance = connection;
        }

        internal void Open()
        {
            //////////////////////////////////////////
            // Step 1: Get Exclusive lock
            Monitor.Enter(this);
            if (hasBeenOpened)
                return; // Already opened

            //////////////////////////////////////////
            // Step 3: Open connection
            try
            {
                connectionInstance.Open();
            }
            catch
            {
                // remove exclusive lock
                Monitor.Exit(this);
                throw; // re-throw the exception
            }

            hasBeenOpened = true; // Open worked!
        }

        internal void Close()
        {
            if (!hasBeenOpened) // Not open!
                return;

            // Close connection
            connectionInstance.Close();

            hasBeenOpened = false;

            // Remove exclusive access
            Monitor.Exit(this);
        }
    }
}
